package com.yupi.yupao.interceptor;

import com.yupi.yupao.common.BaseContext;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @Author: Peter
 * @Date: 2024-10-07-00:51
 * @Description: Pe
 */
public class CustomHandshakeInterceptor implements HandshakeInterceptor {



    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {


        // 在握手之前执行的逻辑
        String userId =String.valueOf(BaseContext.getCurrentId()) ;
        if (userId == null) {
            return false; // 如果没有用户ID，拒绝连接
        }

        attributes.put("userId", userId); // 将用户ID存入会话属性
        return true; // 允许握手
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        // 在握手之后执行的逻辑
        if (exception != null) {
            System.out.println("握手失败: " + exception.getMessage());
        } else {
            System.out.println("握手成功");
        }
    }
}
